use std::time::Duration;

use anyhow::Result;
use axum::{
    Router,
    http::{Method, header},
};
use routers::api_router;
use state::AppState;
use tower_http::{
    catch_panic::CatchPanicLayer,
    cors::{Any, CorsLayer},
    trace::TraceLayer,
};

mod apis;
mod models;
mod repo;
mod routers;
mod schedule;
mod state;

pub async fn setup_routers() -> Result<Router> {
    let state = AppState::init().await?;

    schedule::start(state.clone()).await;

    let router = Router::new()
        .nest("/api", api_router())
        .layer(TraceLayer::new_for_http())
        .layer(
            CorsLayer::new()
                .allow_credentials(false)
                .allow_origin(Any)
                .allow_methods([
                    Method::GET,
                    Method::POST,
                    Method::PUT,
                    Method::PATCH,
                    Method::DELETE,
                ])
                .allow_headers([
                    header::AUTHORIZATION,
                    header::ACCEPT,
                    header::ORIGIN,
                    header::ACCEPT_LANGUAGE,
                    header::CONTENT_TYPE,
                ])
                .max_age(Duration::from_secs(3600)),
        )
        .layer(CatchPanicLayer::new())
        .with_state(state);

    Ok(router)
}
